from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin,DestroyModelMixin, UpdateModelMixin
from book.models import BookInfo
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.throttling import UserRateThrottle
from rest_framework.filters import OrderingFilter

from . import serializer


# 自定义Pagination类，来为视图添加不同分页行为。在视图中通过pagination_clas属性来指明。
class LargeResultsSetPagination(PageNumberPagination):
    page_size = 3
    page_size_query_param = 'page_size'
    max_page_size = 10


class Books(CreateModelMixin,ListModelMixin,GenericAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = serializer.BookSerializer
    # 用户认证
    authentication_classes = (BasicAuthentication, SessionAuthentication)
    # 用户全限
    permission_classes = (IsAuthenticated,)
    # 设置可访问次数
    throttle_classes = (UserRateThrottle,)
    # 在视图中添加filter_fields属性，指定可以过滤的字段
    filter_fields = ('btitle', 'bread')  # http://127.0.0.1:8000/bookdrf_mixin/?btitle=射雕英雄传2
    # 在视图中添加排序方式，以及指定对应字段
    filter_backends = [OrderingFilter]
    ordering_fields = ('id', 'bread', 'bpub_date')
    # 指定使用分页器
    pagination_class = LargeResultsSetPagination

    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.create(request)


class BookDRFView(GenericAPIView,UpdateModelMixin,DestroyModelMixin):
    """
        获取单一和更新和删除
    """

    queryset = BookInfo.objects.all()  # 指定当前类视图使用的查询集数据
    serializer_class = serializer.BookSerializer  # 指定当前类视图使用的序列化器

    def put(self, request, pk):
       return self.update(request, pk)

    def delete(self, request, pk):
        return self.destroy(request, pk)